/**
 * 压缩中等大小的图片（30KB-65KB）
 */
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');

// 需要压缩的中等大小图片列表
const MEDIUM_IMAGES = [
  'miniprogram/images/discovers/png/dongguahaidai.png',     // 64.94 KB
  'miniprogram/images/discovers/png/nengliangbang.png',     // 64.35 KB
  'miniprogram/images/discovers/png/fanqiedanhua.png',      // 52.64 KB
  'miniprogram/images/discovers/png/jitangdoufugeng.png',   // 45.59 KB
  'miniprogram/images/discovers/png/shalapeizhimajiang.png',// 44.87 KB
  'miniprogram/images/meals/lunch2.png',                    // 44.76 KB
  'miniprogram/images/meals/breakfast1.png',                // 43.33 KB
  'miniprogram/images/discovers/png/qingzhengluyu.png',     // 42.59 KB
  'miniprogram/images/discovers/png/xilanhua.png',          // 40.50 KB
  'miniprogram/images/meals/dinner1.png',                   // 40.23 KB
  'miniprogram/images/discovers/png/sanwenyu.png',          // 39.35 KB
  'miniprogram/images/meals/lunch3.png',                    // 38.50 KB
  'miniprogram/images/discovers/png/doufu.png',             // 38.23 KB
  'miniprogram/images/meals/lunch1.png',                    // 37.94 KB
  'miniprogram/images/meals/breakfast2.png',                // 37.46 KB
  'miniprogram/images/discovers/png/qingjiaoshishu.png',    // 34.02 KB
  'miniprogram/images/recipes/vegetables.jpg',              // 34.02 KB
  'miniprogram/images/discovers/png/jixongrou.png',         // 33.87 KB
  'miniprogram/images/meals/dinner2.png'                    // 29.61 KB
];

// 目标大小（KB）
const TARGET_SIZE = 25;

// 输出目录
const OUTPUT_DIR = 'medium_compressed';
if (!fs.existsSync(OUTPUT_DIR)) {
  fs.mkdirSync(OUTPUT_DIR);
}

// 压缩单张图片
async function compressImage(imagePath) {
  try {
    if (!fs.existsSync(imagePath)) {
      console.log(`文件不存在: ${imagePath}`);
      return { path: imagePath, status: 'not_found' };
    }

    const fileName = path.basename(imagePath);
    const outputPath = path.join(OUTPUT_DIR, fileName);
    const originalSize = fs.statSync(imagePath).size / 1024;
    
    console.log(`处理图片: ${imagePath} (${originalSize.toFixed(2)}KB)`);

    // 加载图片
    let image = sharp(imagePath);
    const metadata = await image.metadata();
    
    // 计算压缩比例
    const scale = 0.9; // 先尝试略微缩小尺寸
    const width = Math.floor(metadata.width * scale);
    
    console.log(`  尺寸: ${metadata.width}x${metadata.height} -> ${width}x${Math.floor(metadata.height * scale)}`);
    
    // 根据图片类型选择压缩方法
    const ext = path.extname(imagePath).toLowerCase();
    
    let buffer;
    if (ext === '.jpg' || ext === '.jpeg') {
      buffer = await image
        .resize(width)
        .jpeg({ quality: 75 })
        .toBuffer();
    } else if (ext === '.png') {
      buffer = await image
        .resize(width)
        .png({ quality: 75 })
        .toBuffer();
    } else {
      buffer = await image
        .resize(width)
        .webp({ quality: 75 })
        .toBuffer();
    }
    
    let compressedSize = buffer.length / 1024;
    
    // 如果还是超过目标大小，尝试进一步压缩
    if (compressedSize > TARGET_SIZE) {
      // 对于PNG文件，尝试转换为JPEG
      if (ext === '.png') {
        console.log(`  尝试转换为JPEG以减小体积...`);
        buffer = await image
          .resize(width)
          .jpeg({ quality: 75 })
          .toBuffer();
        
        compressedSize = buffer.length / 1024;
      }
      
      // 如果仍然太大，继续降低质量和尺寸
      if (compressedSize > TARGET_SIZE) {
        console.log(`  进一步压缩...`);
        const newWidth = Math.floor(width * 0.8);
        
        if (ext === '.jpg' || ext === '.jpeg' || ext === '.png') {
          buffer = await image
            .resize(newWidth)
            .jpeg({ quality: 65 })
            .toBuffer();
        } else {
          buffer = await image
            .resize(newWidth)
            .webp({ quality: 65 })
            .toBuffer();
        }
        
        compressedSize = buffer.length / 1024;
      }
    }
    
    // 保存压缩后的图片
    fs.writeFileSync(outputPath, buffer);
    console.log(`  保存到输出目录: ${outputPath}`);
    
    // 直接替换原始文件
    fs.writeFileSync(imagePath, buffer);
    console.log(`  替换原始文件`);
    
    // 计算减少的体积
    const reduction = originalSize - compressedSize;
    const reductionPercent = (reduction / originalSize) * 100;
    
    console.log(`  压缩结果: ${originalSize.toFixed(2)}KB -> ${compressedSize.toFixed(2)}KB (减少 ${reduction.toFixed(2)}KB, ${reductionPercent.toFixed(2)}%)`);
    
    return {
      path: imagePath,
      originalSize,
      newSize: compressedSize,
      reduction
    };
  } catch (error) {
    console.error(`处理失败: ${imagePath}`, error);
    return {
      path: imagePath,
      error: error.message,
      status: 'error'
    };
  }
}

// 主函数
async function main() {
  console.log('开始处理中等大小的图片...');
  
  let totalOriginalSize = 0;
  let totalCompressedSize = 0;
  let successCount = 0;
  let errorCount = 0;
  
  for (const imgPath of MEDIUM_IMAGES) {
    try {
      const result = await compressImage(imgPath);
      
      if (result.status !== 'error' && result.status !== 'not_found') {
        totalOriginalSize += result.originalSize;
        totalCompressedSize += result.newSize;
        successCount++;
      } else {
        errorCount++;
      }
      
      console.log('-'.repeat(50));
    } catch (error) {
      console.error(`处理出错:`, error);
      errorCount++;
    }
  }
  
  console.log('\n中等大小图片处理完成:');
  console.log(`总图片数: ${MEDIUM_IMAGES.length}`);
  console.log(`成功处理: ${successCount}`);
  console.log(`处理失败: ${errorCount}`);
  
  if (successCount > 0) {
    const totalReduction = totalOriginalSize - totalCompressedSize;
    const reductionPercent = (totalReduction / totalOriginalSize) * 100;
    
    console.log(`\n总体积变化: ${totalOriginalSize.toFixed(2)}KB -> ${totalCompressedSize.toFixed(2)}KB`);
    console.log(`总减少: ${totalReduction.toFixed(2)}KB (${reductionPercent.toFixed(2)}%)`);
  }
}

// 执行主函数
main().catch(console.error); 